﻿using adb;
using Masuit.Tools;
using Masuit.Tools.Systems;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MQTTnet;
using MQTTnet.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using utils;


namespace VideoCheck.AppCode
{
    public class RunCheckVideo
    {
        private DbContextOptionsBuilder<MyDbContext> myOptionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        private DbContextOptionsBuilder<DeviceDbContext> deviceoOptionsBuilder = new DbContextOptionsBuilder<DeviceDbContext>();
        private IConfigurationRoot configuration;


        private IMqttClient client;
        private MqttClientOptionsBuilder clienOption;
        private MqttFactory mqttFactory;
        public RunCheckVideo()
        {
            this.configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory)
                                             .AddJsonFile("appsettings.json")
                                             .Build();
            myOptionsBuilder.UseSqlServer(configuration["DBStr"]);
            deviceoOptionsBuilder.UseSqlServer(configuration["DBDeviceStr"]);


            this.clienOption = new MqttClientOptionsBuilder();
            this.clienOption.WithClientId(this.configuration["mqttClientId"]);
            this.clienOption.WithTcpServer(this.configuration["mqttServiceIp"], this.configuration["mqttServicePort"].ConvertTo<int>());
            this.clienOption.WithCredentials("admin", "admin");
            this.clienOption.WithNoKeepAlive();
            this.mqttFactory = new MqttFactory();
            this.client = mqttFactory.CreateMqttClient();

            Task fun = new Task(async () =>
            {
                while (true)
                {
                    if (!this.client.IsConnected)
                    {
                        try
                        {
                            var op = this.clienOption.Build();
                            await this.client.ConnectAsync(op);
                        }
                        catch (Exception ex)
                        {
                            writeExceptionLogUtil.writeLogException(ex, "/root/logs", "VideoCheck");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                    Thread.Sleep(2000);
                }
            });
            fun.Start();


        }
        public static List<tPowerStationDevice> videos;
        public static Dictionary<string, DateTime> endTimeList;
        public static int keyModel;

        private async Task setting()
        {
            using (var db = new MyDbContext(myOptionsBuilder.Options))
            {
                videos = await db.tPowerStationDevice.Where(x => x.deviceType_keyId_fk == 820004 && x.dataState == 0).ToListAsync();
                var key = await db.tKey.FirstOrDefaultAsync(x => x.keyId == 820004);
                keyModel = key.keyValue.ConvertTo<int>() * 1000;
            }
        }

        public async void Run()
        {
            await setting();
            foreach (var item in videos)
            {
                _ = Task.Run(() =>
                  {
                          //Console.WriteLine($"截取监控[{item.deviceName}]图,开始{DateTime.Now.ToString()}");
                          ImgCut(item.deviceId);
                          //Console.WriteLine($"截取监控[{item.deviceName}]图,结束{DateTime.Now.ToString()}");
                      });
                Thread.Sleep(1000);
            }
            _ = Task.Run(() => { ImgCheck(); });
        }
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetTimeStamp()
        {
            return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
        }

        public async void ImgCut(long itemId)
        {
            // int itemReSetCheck = 0;
            using (var db = new MyDbContext(myOptionsBuilder.Options))
            {
                var item = await db.tPowerStationDevice.FirstAsync(x => x.deviceId == itemId);
                while (true)
                {
                    // if (itemReSetCheck >= 60*60)
                    // {
                    //     itemReSetCheck = 0;
                    //     item = await db.tPowerStationDevice.FirstAsync(x => x.deviceId == itemId);
                    // }
               
                        //范围内的db 和传进来的item db不是同一个 必须先查
                        //item = await db.tPowerStationDevice.FirstAsync(x => x.deviceId == item.deviceId);
                        var datas = VideoCutImage.GetImageOfVideo(item.deviceDes, configuration["TmpPath"]);
                        if (datas == null || datas.Length == 0)
                        {
                            //由在线状态变为离线才开始推送
                            if ("1".Equals(item.devicePoint))
                            {
                                tPowerStation powerStation = await db.tPowerStation.FirstAsync(x => x.powerStationId == item.devicePowerStation_powerStationId_fk);
                                Console.WriteLine("[" + DateTime.Now + "]Send mqtt ===" + "/" + powerStation.powerStationNo + "/JianKongLiXian/" + item.deviceId);
                                await this.client.PublishStringAsync("/" + powerStation.powerStationNo + "/JianKongLiXian/" + item.deviceId, "{\"alarm\":1}");
                            }
                            item.devicePoint = "0";
                            await db.SaveChangesAsync();
                        }
                        else
                        {
                            var sf = new SnowFlake();
                            tFiles fileModel;
                            string contentType = "image/jpg";
                            string fileExtention = ".jpg";
                            string typeName = "监控截图";
                            string urlPath = "";
                            string cdipath = configuration["SavePath"];
                            urlPath = $"{typeName}/{DateTime.Now:yyyyMMdd}/";
                            cdipath = Path.Combine(cdipath, urlPath);
                            if (!Directory.Exists(cdipath))
                            {
                                Directory.CreateDirectory(cdipath);
                            }
                            string fileupName = sf.GetLongId() + fileExtention;
                            cdipath = Path.Combine(cdipath, fileupName);
                            using (var fileSream = new FileStream(cdipath, FileMode.Create, FileAccess.Write))
                            {
                                await fileSream.WriteAsync(datas);

                            }
                            fileModel = new tFiles()
                            {
                                addTime = DateTime.Now,
                                fileName = "auto.jpg",
                                filePath = urlPath + fileupName,
                                fileDomain = typeName,
                                fileType = contentType
                            };

                            await db.tFiles.AddAsync(fileModel);
                            //这里要先存才有文件ID出来！
                            await db.SaveChangesAsync();
                            item.deviceTopic = fileModel.fileId + "";
                            item.devicePoint = "1";
                            await db.SaveChangesAsync();
                        }
                        // itemReSetCheck += keyModel/1000;
                    
                    Thread.Sleep(keyModel);
                }
            }
        }

        private void ImgCheck()
        {
            while (true)
            {
                try
                {
                    if (Directory.GetDirectories(configuration["SavePath"] + "监控截图").Length >= 2)
                    {
                        Console.WriteLine("shanchuzhong....");
                        string path = configuration["SavePath"] + "监控截图";
                        List<string> filelist = Directory.GetDirectories(path).ToList();
                        // string today = "/" + DateTime.Now.ToString("yyyyMMdd");
                        string yesterday = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                        foreach (var item in filelist)
                        {
                            if (item.EndsWith(yesterday))
                            {
                                Directory.Delete(item, true);
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    writeExceptionLogUtil.writeLogException(ex, "/root/logs", "VideoCheck");
                    // throw;
                }
                Thread.Sleep(24 * 60 * 60 * 1000);
            }
        }
    }
}